package com.example.moonshine.zxing.Activity;

import android.app.Activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.moonshine.zxing.Data.LoginData;
import com.example.moonshine.zxing.Data.RSpostData;
import com.example.moonshine.zxing.Data.ResultData;
import com.example.moonshine.zxing.Data.ReturnPostData;
import com.example.moonshine.zxing.Data.ReturnStatusData;
import com.example.moonshine.zxing.Data.SidSelectData;
import com.example.moonshine.zxing.Data.StaticUser;
import com.example.moonshine.zxing.Data.SysInfoData;
import com.example.moonshine.zxing.Data.UserpassData;
import com.example.moonshine.zxing.Fragment.FirstFragment;
import com.example.moonshine.zxing.Hepler.DataDBHepler;
import com.example.moonshine.zxing.R;
import com.example.moonshine.zxing.Util.DownloadUtil;
import com.example.moonshine.zxing.Util.SavePamasInfo;
import com.example.moonshine.zxing.Util.SelecthttpUserUtil;
import com.example.moonshine.zxing.Util.UpdateDialog;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * Created by moonshine on 2018/1/26.
 */


public class LoginActivity extends Activity {

    private DownloadUtil downloadUtils;

    String url;
    EditText username;
    EditText password;
    Button login_btn;
    String loginUrl = "http://119.23.219.22:80/element-admin/user/login";
    DataDBHepler dbHepler;
    String result;
    String Username;
    String Password;
    SavePamasInfo mSavePamasInfo = new SavePamasInfo();
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        UltimateBar.newColorBuilder()
                .statusColor(Color.parseColor("#16abd9"))       // 状态栏颜色
                .statusDepth(50)                // 状态栏颜色深度
                .build(this)
                .apply();
        ViewLayout();
        init();
        dbHepler = new DataDBHepler(getBaseContext());
        try {
            if (dbHepler.isIdoruserpass()) {
                ArrayList<UserpassData> DataList1 = dbHepler.FinduserpassData();
                final UserpassData data1 = new UserpassData(DataList1.get(0).getId(), DataList1.get(0).getUser(), DataList1.get(0).getPassword());
                Username = data1.getUser();
                Password = data1.getPassword();
            }
            else {
                Log.i(TAG,"没有用户名");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        username.setLines(1);
        password.setLines(1);
        username.setText(Username);
        password.setText(Password);
        username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                username.setCursorVisible(true);
            }
        });
        password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                password.setCursorVisible(true);
            }
        });

        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo == null || !networkInfo.isAvailable()) {
                    Toast.makeText(getApplicationContext(), "网络未连接", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            try {
                                if(username.getText().toString().equals("")||password.getText().toString().equals(""))
                                {
                                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                                }else {
                                    result = GetPostLogin(username.getText().toString(), password.getText().toString(), loginUrl);
//                                StaticUser.setUser(username.getText().toString());
                                    if (result.equals("10")) {

                                        SavePamasInfo savePamasInfo = new SavePamasInfo();

                                        savePamasInfo.saveInfo(LoginActivity.this,"user",username.getText().toString().trim(),"login");

                                        if (dbHepler.isIdoruserpass()) {
                                            dbHepler.updateUserpass(username.getText().toString(), password.getText().toString());
                                        } else {
                                            dbHepler.addUserpass("1", username.getText().toString().trim(), password.getText().toString().trim());
                                        }
                                        Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();//提示用户登录成功
                                        Intent intent = new Intent();
                                        intent.setClass(LoginActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    } else if (result.equals("12")) {
                                        Toast.makeText(getApplicationContext(), "登录失败，服务器故障", Toast.LENGTH_SHORT).show();//提示用户登录失败
                                    } else if (result.equals("14")) {
                                        Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();//提示用户登录成功
                                        Intent intent = new Intent();
                                        intent.setClass(LoginActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "登录失败，用户名或密码错误", Toast.LENGTH_SHORT).show();//提示用户登录失败
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(LoginActivity.this, "网络错误或服务器故障", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        }
                    }).start();
                }
            }
        });
    }
        //控件初始化
    public void ViewLayout() {
        login_btn = findViewById(R.id.login_btn);
        username = findViewById(R.id.login_user);
        password = findViewById(R.id.login_psw);
    }

    public void init() {
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        if (url.equals("null")) {
            Log.i(TAG, "已经为最新版本");
        } else {
            Log.i(TAG, "该下载链接为:" + url);
            showDialog();
        }
    }
    public void showDialog() {
            downloadUtils =   new DownloadUtil(LoginActivity.this);
            final UpdateDialog Dialog = new UpdateDialog(LoginActivity.this);
            Dialog.setTitle("消息提示");
            Dialog.setMessage("发现新版本，是否更新?");
            Dialog.setYesOnclickListener("确定", new UpdateDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    downloadUtils.downloadAPK(url, "apk");
                    Dialog.dismiss();
                }
            });
            Dialog.setNoOnclickListener("取消", new UpdateDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    Dialog.dismiss();
                }
            });
            Dialog.show();
        }

    public String GetPostLogin(String uname, String upsd,String path) {
        //okhttp Post请求传输Json数据
        OkHttpClient client = new OkHttpClient();
        LoginData Ldata = new LoginData();
        String postStatus = null;
        Ldata.setUname(uname);
        Ldata.setUpwd(upsd);
        Ldata.setModule("AN1");
        Gson gson = new Gson();
        String json = gson.toJson(Ldata);//将其转换为JSON数据格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, json);//放进requestBoday中
        Request request = new Request.Builder()
                .url(path)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            ReturnStatusData resultStatusData= gson.fromJson(result,ReturnStatusData.class);
            postStatus= resultStatusData.getStatus();
            Log.i(TAG, "GetPostLogin: "+postStatus);
            String resultSid = resultStatusData.getSid();
            String resultSysInfo = resultStatusData.getSystemInfo();
            List<SysInfoData> sysInfoData =gson.fromJson(resultSysInfo,new TypeToken<List<SysInfoData>>(){}.getType());
            Log.i(TAG,"SID为"+resultSid);
            Log.i(TAG,"SysId为"+resultSysInfo);
            Log.i(TAG,"列表为"+sysInfoData);
            List sysId =new ArrayList<>();
            List sysname = new ArrayList<>();
            try {
                for (int i=0;i<sysInfoData.size();i++)
                {
                    sysId.add(sysInfoData.get(i).getSysId());
                    sysname.add(sysInfoData.get(i).getSysName());
                    Log.i("tag","sysid："+sysInfoData.get(i).getSysId());
                }
                mSavePamasInfo.saveInfo(this,"sysname",String.valueOf(sysname).replace("[","").replace("]",""),"login");
                if (dbHepler.isIdorSid()) {
                    dbHepler.update(resultSid, String.valueOf(sysId));
                } else {
                    dbHepler.add("1", resultSid, String.valueOf(sysId));
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return postStatus;
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.down_in, R.anim.down_out);
    }
 }
